<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\Member\Repository\Member;
use App\Repositories\DistributeRepository;
use Closure;
use Illuminate\Support\Facades\Auth;

class WechatAuth
{
    protected $distributeRepository;

    public function __construct()
    {
        $this->distributeRepository = new DistributeRepository();
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if (session('wechat.oauth_user')) {
            $user = session('wechat.oauth_user');
            $user = $user->toArray();
            $userInfo = $user['original'];
            $member = Member::where('openid', $userInfo['openid'])->first();
            if (!$member) {
                $member = new Member();
                $member->openid = $userInfo['openid'];
                $member->nickname = $userInfo['nickname'];
                $member->headimgurl = $userInfo['headimgurl'];
                $member->sex = $userInfo['sex'];
                $member->city = $userInfo['city'];
                $member->province = $userInfo['province'];
                $member->country = $userInfo['country'];
                $member->save();
                Auth::guard('member')->loginUsingId($member->id);
                //新创建的用执行分销bind关系
                $this->bindDistribute($request);
            } else {
                Auth::guard('member')->loginUsingId($member->id);
            }
            $user = Auth::guard('member')->user();
            if($user->status==\App\Http\Controllers\Admin\Member\Service\Member::OFF){
                abort(403,'no message');
            }
        }
        return $next($request);
    }

    public function bindDistribute($request)
    {
        $firstLeader = $request->firstLeader;
        if ($request->firstLeader) {
            $user_id = Auth::guard('member')->user()->id;
            if (!$this->distributeRepository->isHasLeader($user_id)) {

                $this->distributeRepository->distribute($firstLeader, $user_id);
            }
        }
    }
}
